﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace Services.ViewModel
{
    public class BaseWebService
    {
        IRestfulHttpClient restClient;
        IHttpResponseMessage readingData;
        public Uri BaseUri { get; set; }
        public BaseWebService(Uri baseUri)
        {
            BaseUri = baseUri;
            restClient = new RestfulHttpClient(BaseUri);
        }
        private async Task<string> DoPostAsync(string serviceQueryStringAndParams, string data)
        {
            try
            {
                IHttpResponseMessage responseMessage = await DoPostBasicAsync(serviceQueryStringAndParams, data);
                return await responseMessage.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return default(string);
            }
        }
        protected virtual Task<IHttpResponseMessage> DoPostBasicAsync(string serviceQueryStringAndParams, string param)
        {
            return restClient.PostFormUrlEncodedAsync(serviceQueryStringAndParams, param);
        }
        //protected async Task<T> DoGetJonAsync<T>(string serviceQueryStringAndParams,string parms)
        //{
        //    try
        //    {
        //        string responseText = await DoGetAsync(serviceQueryStringAndParams, parms);
        //        var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseText));
        //        var ser = new DataContractJsonSerializer(typeof(T));
        //        return await Task.Run(()=>(T)ser.ReadObject(ms));
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception("Exception calling GetGenericRequestAndDeserialize", ex);
        //    }

        //}
        public async Task<T> DoPostJonAsync<T>(string serviceQueryStringAndParams, string parms)
        {
            try
            {
                string responseText = await DoPostAsync(serviceQueryStringAndParams, parms);
                if(string.IsNullOrEmpty(responseText))
                    return default(T);
                var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseText));
                var ser = new DataContractJsonSerializer(typeof(T));
                return await Task.Run(() => (T)ser.ReadObject(ms));
            }
            catch (Exception ex)
            {
                return default(T);
            }

        }

    }
}
